﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using Devv.Core.Erroo;
using Devv.Core.Utils;
using Devv.Support.Client;

namespace Devv.FreshTracker
{
	public class Maintenance
	{
		#region Properties

		private static String LogPath { get { return App.DataPath + "/Debug.log"; } }

		#endregion

		#region Run

		public static void Run(Object state)
		{
			if (DateTime.Now.DayOfWeek == DayOfWeek.Monday || DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || DateTime.Now.DayOfWeek == DayOfWeek.Friday)
			{
				if (Options.CheckUpdates)
				{
					CheckForUpdates();
				}

				CleanLog();
			}
			else
			{
				ReportErrors();
			}
		}

		#endregion

		#region Version and updates

		public static void CheckForUpdates()
		{
			try
			{
				using (WebClient client = new WebClient())
				{
					String url = ConfigUtil.GetConfig("Devv.AppUrl");
					String installed = AssemblyUtil.GetFriendlyVersion(Assembly.GetEntryAssembly()).Replace(".", String.Empty);
					String latest = client.DownloadString(url + "Version.txt").Replace(".", String.Empty);

					Boolean b = Convert.ToInt32(installed.Substring(0, 3)) < Convert.ToInt32(latest.Substring(0, 3));

					if (b)
					{
						Log("New version available to download " + latest);

						if (MessageBox.Show(Messages.NewVersionAvailable, Messages.Update, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
						{
							Process.Start(url + "#Download");
						}
					}
					else
					{
						Log("No new version available to download.");
					}
				}
			}
			catch (Exception ex)
			{
				if (NetworkUtil.IsConnected())
				{
					ErrorHandler.Handle(ex);
				}
			}
		}

		#endregion

		#region Error reporting

		public static void ReportErrors()
		{
			Int32 count = IOUtil.CountFiles(Config.LogPath);

			if (count > 50)
			{
				if (MessageBox.Show(Messages.PleaseReportErrors, Messages.Confirm, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
				{
					Options.ReportErrors = true;
				}
			}

			if (!Options.ReportErrors || !NetworkUtil.IsConnected())
			{
				return;
			}

			String errors = Reporter.GetLoggedErrors(Config.LogPath);

			if (errors.Length > 10)
			{
				try
				{
					Reporter.SendErrors("FreshTracker", Options.UserName, errors);

					Log("Sent error reports to Devv.");
				}
				catch
				{
					IOUtil.WriteFile(Config.LogPath + "Reports-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".htm", errors);
				}
			}
		}

		#endregion

		#region Logging

		public static void Log(String message, Boolean extraLine = false)
		{
			if (!Options.Debug)
			{
				return;
			}

			String line = DateTime.Now.ToString("yyMMdd - HH:mm:ss") + ": " + message + Environment.NewLine;

			if (extraLine)
			{
				line += Environment.NewLine;
			}

			try
			{
				IOUtil.WriteFile(LogPath, line, true);
			}
			catch
			{
				// Don't want to alert or keep tracking log errors, right?
			}
		}

		private static void CleanLog()
		{
			if (!Options.Debug)
			{
				return;
			}

			FileInfo file = new FileInfo(LogPath);

			if (file == null || file.Exists)
			{
				return;
			}

			Int32 length = Convert.ToInt32(file.Length);

			if (length > 600000)
			{
				try
				{
					File.WriteAllText(LogPath, File.ReadAllText(LogPath).Substring(length - 500000, 500000));
				}
				catch
				{
					// Don't want to alert or keep tracking log errors, right?
				}
			}

		}

		#endregion
	}
}